<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Notice;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class NoticeController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Notice(), function (Grid $grid) {
            $grid->model()->orderBy('type')->orderBy('created_at','desc');
            $grid->column('id')->sortable();
            $grid->column('title');
            $grid->column('content');
            $grid->column('type')->using([1 => '代理通知', 2 => '用户通知'])->label([
                'default' => 'primary', // 设置默认颜色，不设置则默认为 default
                1 => 'primary',
                2 => 'success',
            ]);
            $grid->column('show')->switch();
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
        
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
        
            });
            $grid->enableDialogCreate();
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Notice(), function (Show $show) {
            $show->field('id');
            $show->field('title');
            $show->field('content');
            $show->field('type');
            $show->field('show');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Notice(), function (Form $form) {
            $form->display('id');
            $form->text('title');
            $form->text('content')->required();
            $form->radio('type')->options([1 => '代理通知', 2=>'用户通知'])->default(1);
            $form->switch('show')->default(1);
        
            $form->display('created_at');
            $form->display('updated_at');

            //编辑缓存同步
            $form->saved(function(Form $form){
                if($form->model()->type == 2){
                    cache()->forget('user_notices');
                }
                
            });

            $form->deleted(function (Form $form, $result) {
                // 获取待删除行数据，这里获取的是一个二维数组
                $data = $form->model()->toArray();
                
                // 通过 $result 可以判断数据是否删除成功
                if ( $result) {
                    cache()->forget('user_notices');
                    // 返回删除成功提醒，此处跳转参数无效
                    return $form->response()->success('删除成功');
                }
                return $form->response()->error('数据删除失败');
            });
        });
    }
}
